package network;

import java.io.BufferedReader;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * Listens to a reader and notifies the Messager so that it can parse 
 * commands when they arrive.
 * You have to create a new thread to use this, e.g.
 * Thread t = new Thread(new NetworkListener(this,myBufferedReader));
 * t.start();
 * @author CodyS
 *
 */
class NetworkListener implements Runnable {
	private BufferedReader br;
	private Messager receiver;
	/**
	 * Constructs a new listener, but does not start it running.
	 * @param receiver What to notify when messages are received
	 * @param br The BufferedReader.
	 */
	public NetworkListener(Messager receiver, BufferedReader br) {
		this.br = br;
		this.receiver = receiver;
	}
	/** 
	 * Starts listening, but remember to use this only as a thread.
	 */
	public void run() {
		String s;
		try {
			while((s=br.readLine())!=null) {
				try {
					receiver.receive(new JSONObject(s));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}